#include "../Include/course_pub.h"
#include "../Include/common_pub.h"
#include "../globals.h"
#include <stdio.h>
#include <string.h>

int add_course(const char* id, const char* name, const char* type, 
               int hours, float credit, int max_students) {
    if (course_count >= MAX_COURSES_NUM) {
        return FULL;
    }
    
    for (int i = 0; i < course_count; i++) {
        if (strcmp(courses[i].id, id) == 0) {
            return DUPLICATE;
        }
    }
    
    strcpy(courses[course_count].id, id);
    strcpy(courses[course_count].name, name);
    strcpy(courses[course_count].type, type);
    courses[course_count].hours = hours;
    courses[course_count].credit = credit;
    courses[course_count].max_students = max_students;
    courses[course_count].selected_count = 0;
    
    course_count++;
    log_message(LOG_INFO, "添加课程: %s %s", id, name);
    return SUCCESS;
}

Course* find_course(const char* id) {
    for (int i = 0; i < course_count; i++) {
        if (strcmp(courses[i].id, id) == 0) {
            return &courses[i];
        }
    }
    return NULL;
}

void display_all_courses() {
    printf("\n=== 所有课程信息 ===\n");
    if (course_count == 0) {
        printf("暂无课程信息\n");
        return;
    }
    
    for (int i = 0; i < course_count; i++) {
        printf("课程号: %s, 名称: %s, 类型: %s\n", 
               courses[i].id, courses[i].name, courses[i].type);
        printf("  学时: %d, 学分: %.1f, 人数: %d/%d\n",
               courses[i].hours, courses[i].credit,
               courses[i].selected_count, courses[i].max_students);
    }
}

int delete_course(const char* id) { 
    for (int i = 0; i < course_count; i++) {
        if (strcmp(courses[i].id, id) == 0) {
            for (int j = i; j < course_count - 1; j++) {
                courses[j] = courses[j + 1];
            }
            course_count--;
            log_message(LOG_INFO, "删除课程: %s", id);
            return SUCCESS;
        }
    }
    return NOT_FOUND;
}

int update_course(const char* id, const char* new_name, const char* new_type,
                  int new_hours, float new_credit, int new_max) { 
    Course* course = find_course(id);
    if (course == NULL) return NOT_FOUND;
    
    strcpy(course->name, new_name);
    strcpy(course->type, new_type);
    course->hours = new_hours;
    course->credit = new_credit;
    course->max_students = new_max;
    
    log_message(LOG_INFO, "更新课程: %s", id);
    return SUCCESS;
}
